package api

import (
	"context"
	"encoding/json"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/gorilla/mux"
)

// APIHandler 处理REST API请求
type APIHandler struct {
	userService UserService
}

// NewAPIHandler 创建一个新的API处理器
func NewAPIHandler(userService UserService) *APIHandler {
	return &APIHandler{
		userService: userService,
	}
}

// CreateRouter 创建REST API路由器
func (h *APIHandler) CreateRouter() *mux.Router {
	router := mux.NewRouter()

	// 公开路由（不需要认证）
	public := router.PathPrefix("/api/v1").Subrouter()
	public.HandleFunc("/login", h.handleLogin).Methods("POST")
	public.HandleFunc("/register", h.handleRegister).Methods("POST")

	// 受保护路由（需要认证）
	protected := router.PathPrefix("/api/v1").Subrouter()
	protected.Use(h.authMiddleware)

	// 用户管理路由
	users := protected.PathPrefix("/users").Subrouter()
	users.HandleFunc("", h.handleGetUsers).Methods("GET")
	users.HandleFunc("", h.handleCreateUser).Methods("POST")
	users.HandleFunc("/{id}", h.handleGetUser).Methods("GET")
	users.HandleFunc("/{id}", h.handleUpdateUser).Methods("PUT")
	users.HandleFunc("/{id}", h.handleDeleteUser).Methods("DELETE")

	// 角色权限管理路由
	roles := protected.PathPrefix("/roles").Subrouter()
	roles.HandleFunc("", h.handleListRoles).Methods("GET")
	roles.HandleFunc("/{role}", h.handleGetRole).Methods("GET")
	roles.HandleFunc("/{role}", h.handleUpdateRole).Methods("PUT")

	// 用户信息路由
	protected.HandleFunc("/me", h.handleGetMe).Methods("GET")

	// 设备管理路由
	devices := protected.PathPrefix("/devices").Subrouter()
	devices.HandleFunc("", h.handleListDevices).Methods("GET")
	devices.HandleFunc("/{deviceID}", h.handleGetDeviceInfo).Methods("GET")
	devices.HandleFunc("/{deviceID}/data", h.handleGetDeviceData).Methods("GET")
	devices.HandleFunc("/{deviceID}/properties/{propertyName}", h.handleGetDeviceProperty).Methods("GET")

	// 设备属性控制配置路由
	deviceConfigs := protected.PathPrefix("/device-configs").Subrouter()
	deviceConfigs.HandleFunc("", h.handleCreateDevicePropertyConfig).Methods("POST")
	deviceConfigs.HandleFunc("", h.handleListDevicePropertyConfigs).Methods("GET")
	deviceConfigs.HandleFunc("/{id}", h.handleGetDevicePropertyConfig).Methods("GET")
	deviceConfigs.HandleFunc("/{id}", h.handleUpdateDevicePropertyConfig).Methods("PUT")
	deviceConfigs.HandleFunc("/{id}", h.handleDeleteDevicePropertyConfig).Methods("DELETE")

	return router
}

// 认证中间件
func (h *APIHandler) authMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 从Authorization头中提取token
		authHeader := r.Header.Get("Authorization")
		if authHeader == "" {
			h.writeError(w, http.StatusUnauthorized, "Authorization header is required")
			return
		}

		// 验证Authorization头格式
		bearerToken := strings.Split(authHeader, " ")
		if len(bearerToken) != 2 || bearerToken[0] != "Bearer" {
			h.writeError(w, http.StatusUnauthorized, "Invalid authorization format")
			return
		}

		// 验证token
		user, err := h.userService.ValidateToken(bearerToken[1])
		if err != nil {
			h.writeError(w, http.StatusUnauthorized, err.Error())
			return
		}

		// 将用户信息添加到请求上下文
		ctx := context.WithValue(r.Context(), "user", user)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

// 权限检查中间件
func (h *APIHandler) permissionMiddleware(requiredPermission string, next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// 从上下文中获取用户信息
		user, ok := r.Context().Value("user").(*User)
		if !ok {
			h.writeError(w, http.StatusUnauthorized, "User not found in context")
			return
		}

		// 检查权限
		hasPermission, err := h.userService.CheckPermission(user.ID, requiredPermission)
		if err != nil {
			h.writeError(w, http.StatusInternalServerError, "Failed to check permission")
			return
		}

		if !hasPermission {
			h.writeError(w, http.StatusForbidden, "Insufficient permissions")
			return
		}

		next(w, r)
	}
}

// 辅助函数：将错误写入响应
func (h *APIHandler) writeError(w http.ResponseWriter, statusCode int, message string) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(statusCode)
	json.NewEncoder(w).Encode(map[string]string{"error": message})
}

// 辅助函数：将JSON响应写入响应
func (h *APIHandler) writeJSON(w http.ResponseWriter, statusCode int, data interface{}) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(statusCode)
	json.NewEncoder(w).Encode(data)
}

// 登录处理函数
func (h *APIHandler) handleLogin(w http.ResponseWriter, r *http.Request) {
	var loginReq LoginRequest

	// 解析请求体
	if err := json.NewDecoder(r.Body).Decode(&loginReq); err != nil {
		h.writeError(w, http.StatusBadRequest, "Invalid request body")
		return
	}

	// 认证用户
	user, err := h.userService.Authenticate(loginReq.Username, loginReq.Password)
	if err != nil {
		h.writeError(w, http.StatusUnauthorized, err.Error())
		return
	}

	// 生成token
	token, err := h.userService.GenerateToken(user)
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to generate token")
		return
	}

	// 计算token过期时间
	expires := time.Now().Add(24 * time.Hour).Unix() // 24小时后过期

	// 返回响应
	response := LoginResponse{
		Token:   token,
		UserID:  user.ID,
		Role:    user.Role,
		Expires: expires,
	}

	h.writeJSON(w, http.StatusOK, response)
}

// 注册处理函数
func (h *APIHandler) handleRegister(w http.ResponseWriter, r *http.Request) {
	var user User

	// 解析请求体
	if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
		h.writeError(w, http.StatusBadRequest, "Invalid request body")
		return
	}

	// 创建用户
	if err := h.userService.CreateUser(&user); err != nil {
		h.writeError(w, http.StatusBadRequest, err.Error())
		return
	}

	// 创建成功，不返回密码
	user.Password = ""
	h.writeJSON(w, http.StatusCreated, user)
}

// 获取当前用户信息
func (h *APIHandler) handleGetMe(w http.ResponseWriter, r *http.Request) {
	// 从上下文中获取用户信息
	user, ok := r.Context().Value("user").(*User)
	if !ok {
		h.writeError(w, http.StatusUnauthorized, "User not found in context")
		return
	}

	// 获取完整的用户信息
	fullUser, err := h.userService.GetUserByID(user.ID)
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to get user info")
		return
	}

	h.writeJSON(w, http.StatusOK, fullUser)
}

// 获取用户列表
func (h *APIHandler) handleGetUsers(w http.ResponseWriter, r *http.Request) {
	// 解析分页参数
	pageStr := r.URL.Query().Get("page")
	pageSizeStr := r.URL.Query().Get("pageSize")

	// 默认值
	page := 1
	pageSize := 10

	// 转换分页参数
	if pageStr != "" {
		if p, err := strconv.Atoi(pageStr); err == nil && p > 0 {
			page = p
		}
	}

	if pageSizeStr != "" {
		if ps, err := strconv.Atoi(pageSizeStr); err == nil && ps > 0 && ps <= 100 {
			pageSize = ps
		}
	}

	// 获取用户列表
	users, total, err := h.userService.ListUsers(page, pageSize)
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to get users")
		return
	}

	// 返回响应
	response := map[string]interface{}{
		"users":    users,
		"total":    total,
		"page":     page,
		"pageSize": pageSize,
		"pages":    (total + pageSize - 1) / pageSize, // 总页数
	}

	h.writeJSON(w, http.StatusOK, response)
}

// 创建用户
func (h *APIHandler) handleCreateUser(w http.ResponseWriter, r *http.Request) {
	// 检查权限
	user := r.Context().Value("user").(*User)
	hasPermission, _ := h.userService.CheckPermission(user.ID, "write_user")
	if !hasPermission {
		h.writeError(w, http.StatusForbidden, "Insufficient permissions")
		return
	}

	var newUser User

	// 解析请求体
	if err := json.NewDecoder(r.Body).Decode(&newUser); err != nil {
		h.writeError(w, http.StatusBadRequest, "Invalid request body")
		return
	}

	// 创建用户
	if err := h.userService.CreateUser(&newUser); err != nil {
		h.writeError(w, http.StatusBadRequest, err.Error())
		return
	}

	// 创建成功，不返回密码
	newUser.Password = ""
	h.writeJSON(w, http.StatusCreated, newUser)
}

// 获取单个用户
func (h *APIHandler) handleGetUser(w http.ResponseWriter, r *http.Request) {
	// 获取用户ID
	vars := mux.Vars(r)
	userID := vars["id"]

	// 获取用户
	user, err := h.userService.GetUserByID(userID)
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to get user")
		return
	}

	if user == nil {
		h.writeError(w, http.StatusNotFound, "User not found")
		return
	}

	h.writeJSON(w, http.StatusOK, user)
}

// 更新用户
func (h *APIHandler) handleUpdateUser(w http.ResponseWriter, r *http.Request) {
	// 获取用户ID
	vars := mux.Vars(r)
	userID := vars["id"]

	// 检查权限
	requester := r.Context().Value("user").(*User)
	// 只有管理员或用户本人可以更新用户信息
	if requester.Role != "admin" && requester.ID != userID {
		h.writeError(w, http.StatusForbidden, "Insufficient permissions")
		return
	}

	var updatedUser User

	// 解析请求体
	if err := json.NewDecoder(r.Body).Decode(&updatedUser); err != nil {
		h.writeError(w, http.StatusBadRequest, "Invalid request body")
		return
	}

	// 设置用户ID
	updatedUser.ID = userID

	// 更新用户
	if err := h.userService.UpdateUser(&updatedUser); err != nil {
		h.writeError(w, http.StatusBadRequest, err.Error())
		return
	}

	// 获取更新后的用户信息
	user, err := h.userService.GetUserByID(userID)
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to get updated user")
		return
	}

	h.writeJSON(w, http.StatusOK, user)
}

// 删除用户
func (h *APIHandler) handleDeleteUser(w http.ResponseWriter, r *http.Request) {
	// 获取用户ID
	vars := mux.Vars(r)
	userID := vars["id"]

	// 检查权限
	requester := r.Context().Value("user").(*User)
	// 只有管理员可以删除用户，且不能删除自己
	if requester.Role != "admin" || requester.ID == userID {
		h.writeError(w, http.StatusForbidden, "Insufficient permissions")
		return
	}

	// 删除用户
	if err := h.userService.DeleteUser(userID); err != nil {
		h.writeError(w, http.StatusInternalServerError, err.Error())
		return
	}

	// 返回成功响应
	h.writeJSON(w, http.StatusOK, map[string]string{"message": "User deleted successfully"})
}

// 列出所有角色
func (h *APIHandler) handleListRoles(w http.ResponseWriter, r *http.Request) {
	// 检查权限
	user := r.Context().Value("user").(*User)
	hasPermission, _ := h.userService.CheckPermission(user.ID, "manage_roles")
	if !hasPermission {
		h.writeError(w, http.StatusForbidden, "Insufficient permissions")
		return
	}

	// 这里简化实现，返回预定义的角色列表
	roles := []string{"admin", "operator", "viewer"}

	h.writeJSON(w, http.StatusOK, roles)
}

// 获取角色权限
func (h *APIHandler) handleGetRole(w http.ResponseWriter, r *http.Request) {
	// 获取角色名称
	vars := mux.Vars(r)
	role := vars["role"]

	// 获取角色权限
	rolePerm, err := h.userService.GetRolePermission(role)
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to get role permissions")
		return
	}

	if rolePerm == nil {
		h.writeError(w, http.StatusNotFound, "Role not found")
		return
	}

	h.writeJSON(w, http.StatusOK, rolePerm)
}

// 更新角色权限
func (h *APIHandler) handleUpdateRole(w http.ResponseWriter, r *http.Request) {
	// 获取角色名称
	vars := mux.Vars(r)
	role := vars["role"]

	// 检查权限
	user := r.Context().Value("user").(*User)
	hasPermission, _ := h.userService.CheckPermission(user.ID, "manage_roles")
	if !hasPermission {
		h.writeError(w, http.StatusForbidden, "Insufficient permissions")
		return
	}

	var rolePerm RolePermission

	// 解析请求体
	if err := json.NewDecoder(r.Body).Decode(&rolePerm); err != nil {
		h.writeError(w, http.StatusBadRequest, "Invalid request body")
		return
	}

	// 设置角色名称（从URL参数获取，防止修改）
	rolePerm.Role = role

	// 更新角色权限
	if err := h.userService.UpdateRolePermission(&rolePerm); err != nil {
		h.writeError(w, http.StatusInternalServerError, err.Error())
		return
	}

	// 获取更新后的角色权限
	updatedRolePerm, err := h.userService.GetRolePermission(role)
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to get updated role permissions")
		return
	}

	h.writeJSON(w, http.StatusOK, updatedRolePerm)
}

// 获取设备列表
func (h *APIHandler) handleListDevices(w http.ResponseWriter, r *http.Request) {
	// 检查权限
	requester := r.Context().Value("user").(*User)
	hasPermission, err := h.userService.CheckPermission(requester.ID, "read_device")
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to check permission")
		return
	}
	if !hasPermission {
		h.writeError(w, http.StatusForbidden, "Insufficient permissions")
		return
	}

	// 解析分页参数
	pageStr := r.URL.Query().Get("page")
	pageSizeStr := r.URL.Query().Get("pageSize")

	// 默认值
	page := 1
	pageSize := 10

	// 转换分页参数
	if pageStr != "" {
		if p, err := strconv.Atoi(pageStr); err == nil && p > 0 {
			page = p
		}
	}

	if pageSizeStr != "" {
		if ps, err := strconv.Atoi(pageSizeStr); err == nil && ps > 0 && ps <= 100 {
			pageSize = ps
		}
	}

	// 获取设备列表
	devices, total, err := h.userService.ListDevices(page, pageSize)
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to get devices: "+err.Error())
		return
	}

	// 返回响应
	response := map[string]interface{}{
		"devices":  devices,
		"total":    total,
		"page":     page,
		"pageSize": pageSize,
		"pages":    (total + pageSize - 1) / pageSize, // 总页数
	}

	h.writeJSON(w, http.StatusOK, response)
}

// 获取设备信息
func (h *APIHandler) handleGetDeviceInfo(w http.ResponseWriter, r *http.Request) {
	// 检查权限
	requester := r.Context().Value("user").(*User)
	hasPermission, err := h.userService.CheckPermission(requester.ID, "read_device")
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to check permission")
		return
	}
	if !hasPermission {
		h.writeError(w, http.StatusForbidden, "Insufficient permissions")
		return
	}

	// 获取设备ID
	vars := mux.Vars(r)
	deviceID := vars["deviceID"]

	// 获取设备信息
	deviceInfo, err := h.userService.GetDeviceInfo(deviceID)
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to get device info: "+err.Error())
		return
	}

	if deviceInfo == nil {
		h.writeError(w, http.StatusNotFound, "Device not found")
		return
	}

	h.writeJSON(w, http.StatusOK, deviceInfo)
}

// 获取设备数据
func (h *APIHandler) handleGetDeviceData(w http.ResponseWriter, r *http.Request) {
	// 检查权限
	requester := r.Context().Value("user").(*User)
	hasPermission, err := h.userService.CheckPermission(requester.ID, "read_device")
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to check permission")
		return
	}
	if !hasPermission {
		h.writeError(w, http.StatusForbidden, "Insufficient permissions")
		return
	}

	// 获取设备ID
	vars := mux.Vars(r)
	deviceID := vars["deviceID"]
	now := time.Now().Unix()

	// 获取设备数据
	deviceData, err := h.userService.GetDeviceData(deviceID, now)
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to get device data: "+err.Error())
		return
	}

	h.writeJSON(w, http.StatusOK, deviceData)
}

// 获取设备属性
func (h *APIHandler) handleGetDeviceProperty(w http.ResponseWriter, r *http.Request) {
	// 检查权限
	requester := r.Context().Value("user").(*User)
	hasPermission, err := h.userService.CheckPermission(requester.ID, "read_device")
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to check permission")
		return
	}
	if !hasPermission {
		h.writeError(w, http.StatusForbidden, "Insufficient permissions")
		return
	}

	// 获取设备ID和属性名
	vars := mux.Vars(r)
	deviceID := vars["deviceID"]
	propertyName := vars["propertyName"]

	// 获取设备属性
	propertyValue, err := h.userService.GetDeviceProperty(deviceID, propertyName)
	if err != nil {
		// 检查是否是属性不存在的错误
		if strings.Contains(err.Error(), "not found") {
			h.writeError(w, http.StatusNotFound, err.Error())
		} else {
			h.writeError(w, http.StatusInternalServerError, "Failed to get device property: "+err.Error())
		}
		return
	}

	// 返回属性值
	h.writeJSON(w, http.StatusOK, map[string]interface{}{
		"deviceID": deviceID,
		"property": propertyName,
		"value":    propertyValue,
	})

}

// 创建设备属性控制配置
func (h *APIHandler) handleCreateDevicePropertyConfig(w http.ResponseWriter, r *http.Request) {
	// 检查权限
	requester := r.Context().Value("user").(*User)
	hasPermission, err := h.userService.CheckPermission(requester.ID, "write_device")
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to check permission")
		return
	}
	if !hasPermission {
		h.writeError(w, http.StatusForbidden, "Insufficient permissions")
		return
	}

	// 解析请求体
	var config DevicePropertyConfig
	if err := json.NewDecoder(r.Body).Decode(&config); err != nil {
		h.writeError(w, http.StatusBadRequest, "Invalid request body")
		return
	}

	// 创建设置
	if err := h.userService.CreateDevicePropertyConfig(&config); err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to create device property config: "+err.Error())
		return
	}

	// 返回创建成功的配置
	h.writeJSON(w, http.StatusCreated, config)
}

// 获取单个设备属性控制配置
func (h *APIHandler) handleGetDevicePropertyConfig(w http.ResponseWriter, r *http.Request) {
	// 检查权限
	requester := r.Context().Value("user").(*User)
	hasPermission, err := h.userService.CheckPermission(requester.ID, "read_device")
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to check permission")
		return
	}
	if !hasPermission {
		h.writeError(w, http.StatusForbidden, "Insufficient permissions")
		return
	}

	// 获取配置ID
	vars := mux.Vars(r)
	configID := vars["id"]

	// 获取配置
	config, err := h.userService.GetDevicePropertyConfig(configID)
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to get device property config: "+err.Error())
		return
	}

	if config == nil {
		h.writeError(w, http.StatusNotFound, "Config not found")
		return
	}

	// 返回配置
	h.writeJSON(w, http.StatusOK, config)
}

// 列出设备属性控制配置
func (h *APIHandler) handleListDevicePropertyConfigs(w http.ResponseWriter, r *http.Request) {
	// 检查权限
	requester := r.Context().Value("user").(*User)
	hasPermission, err := h.userService.CheckPermission(requester.ID, "read_device")
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to check permission")
		return
	}
	if !hasPermission {
		h.writeError(w, http.StatusForbidden, "Insufficient permissions")
		return
	}

	// 获取查询参数
	deviceID := r.URL.Query().Get("deviceID")
	if deviceID == "" {
		h.writeError(w, http.StatusBadRequest, "deviceID parameter is required")
		return
	}

	// 解析分页参数
	pageStr := r.URL.Query().Get("page")
	pageSizeStr := r.URL.Query().Get("pageSize")

	// 默认值
	page := 1
	pageSize := 10

	// 转换分页参数
	if pageStr != "" {
		if p, err := strconv.Atoi(pageStr); err == nil && p > 0 {
			page = p
		}
	}

	if pageSizeStr != "" {
		if ps, err := strconv.Atoi(pageSizeStr); err == nil && ps > 0 && ps <= 100 {
			pageSize = ps
		}
	}

	// 列出配置
	configs, total, err := h.userService.ListDevicePropertyConfigs(deviceID, page, pageSize)
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to list device property configs: "+err.Error())
		return
	}

	// 返回响应
	response := map[string]interface{}{
		"configs":  configs,
		"total":    total,
		"page":     page,
		"pageSize": pageSize,
		"pages":    (total + pageSize - 1) / pageSize,
	}

	h.writeJSON(w, http.StatusOK, response)
}

// 更新设备属性控制配置
func (h *APIHandler) handleUpdateDevicePropertyConfig(w http.ResponseWriter, r *http.Request) {
	// 检查权限
	requester := r.Context().Value("user").(*User)
	hasPermission, err := h.userService.CheckPermission(requester.ID, "write_device")
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to check permission")
		return
	}
	if !hasPermission {
		h.writeError(w, http.StatusForbidden, "Insufficient permissions")
		return
	}

	// 获取配置ID
	vars := mux.Vars(r)
	configID := vars["id"]

	// 解析请求体
	var config DevicePropertyConfig
	if err := json.NewDecoder(r.Body).Decode(&config); err != nil {
		h.writeError(w, http.StatusBadRequest, "Invalid request body")
		return
	}

	// 设置配置ID
	config.ID = configID

	// 更新配置
	if err := h.userService.UpdateDevicePropertyConfig(&config); err != nil {
		if err.Error() == "config not found" {
			h.writeError(w, http.StatusNotFound, err.Error())
		} else {
			h.writeError(w, http.StatusInternalServerError, "Failed to update device property config: "+err.Error())
		}
		return
	}

	// 获取更新后的配置
	updatedConfig, err := h.userService.GetDevicePropertyConfig(configID)
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to get updated config")
		return
	}

	// 返回更新后的配置
	h.writeJSON(w, http.StatusOK, updatedConfig)
}

// 删除设备属性控制配置
func (h *APIHandler) handleDeleteDevicePropertyConfig(w http.ResponseWriter, r *http.Request) {
	// 检查权限
	requester := r.Context().Value("user").(*User)
	hasPermission, err := h.userService.CheckPermission(requester.ID, "write_device")
	if err != nil {
		h.writeError(w, http.StatusInternalServerError, "Failed to check permission")
		return
	}
	if !hasPermission {
		h.writeError(w, http.StatusForbidden, "Insufficient permissions")
		return
	}

	// 获取配置ID
	vars := mux.Vars(r)
	configID := vars["id"]

	// 删除配置
	if err := h.userService.DeleteDevicePropertyConfig(configID); err != nil {
		if err.Error() == "config not found" {
			h.writeError(w, http.StatusNotFound, err.Error())
		} else {
			h.writeError(w, http.StatusInternalServerError, "Failed to delete device property config: "+err.Error())
		}
		return
	}

	// 返回成功响应
	h.writeJSON(w, http.StatusOK, map[string]string{"message": "Config deleted successfully"})
}
